package com.example.back.utils;

import com.example.back.jpa.AdminRepository;
import com.example.common.entity.Admin;
import com.example.common.support.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @Author wxy
 * @Date 2020/11/11 15:58
 * @Version 1.0
 */
@Slf4j
@Component
public class UserUtils {
    @Resource
    private HttpServletRequest request;
    @Resource
    private AdminRepository sysAdminRepository;

    /**
     * 获取当前登录用户信息
     *
     * @return 用户信息
     */
    public Admin getUser() {
        Long id = Long.valueOf(request.getHeader("UID"));
        if (StringUtils.isEmpty(id)) {
            return null;
        }
        return sysAdminRepository.findById(id).orElseThrow(() -> new ApiException(1, "用户不存在"));
    }

    public Long getUserID() {
        if(request.getHeader("UID") == null)
            return null;
        Long id = Long.valueOf(request.getHeader("UID"));
        if (StringUtils.isEmpty(id)) {
            return null;
        }
        return id;
    }
}
